package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Sampling;
import com.tianxin.workbao.workBao.bean.SamplingDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/26.
 */

public class SamplingProvide extends BaseDataProvide {
    private Integer mPage;
    private List<Sampling> mSamplings;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private SamplingDao samplingDao;
    private boolean isGetData = true;
    private boolean isDeletedata = false;
    private boolean isFromTest = false;


    public SamplingProvide(Context context, UpdateListViewListener listener, boolean from) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        samplingDao = GreenDaoHelper.newInstance().getDaoSession().getSamplingDao();
        isFromTest = from;
    }

    private void getFromDb(int page) {
        Query<Sampling> query = samplingDao.queryBuilder().where(SamplingDao.Properties.Isis.eq(1))
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mSamplings = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (isGetData == false || isDeletedata == true) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (mSamplings != null && !mSamplings.isEmpty()) {
                            mSamplings.clear();
                        }
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mSamplings = BeansUtil.samplingToBeans(dataJson);
                                    refreshUI();
                                    saveToDb(mSamplings);
                                } else {
                                    Sampling sampling = BeansUtil.samplingToBean(dataJson);
                                    mSamplings.add(sampling);
                                    refreshUI();
                                    saveToDb(mSamplings);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("sampling To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false || isDeletedata == true) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                        if (mSamplings != null && !mSamplings.isEmpty()) {
                            mSamplings.clear();
                        }
                        refreshUI();
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mSamplings.size(); i++) {
                samplingDao.insertOrReplace(mSamplings.get(i));
            }
        } else {
            samplingDao.insertOrReplace((Sampling) obj);
        }
    }

    /**
     * get samplings
     *
     * @param page
     */
    public void getdatas(int page) {
        mPage = page;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb(page);
            refreshUI();
        } else {
            updateFromServer();
        }

    }


    /**
     * update the coal data  from server
     */
    private void updateFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("page", mPage + "");
        if (isFromTest == true) {
            map.put("istest", 0 + "");
        } else {
            map.put("istest", 100 + "");
        }
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getSamplingUrl(), params), getDisposeDataHandle());
    }

    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(mSamplings);
        } else {
            mUpdateListViewListener.onRefreshData(mSamplings);
        }
    }

    public void saveSampling(Sampling mSampling) {
        isGetData = false;
        if (mSampling == null) {
            mUpdateListViewListener.showMessage("采样单为空！");
            return;
        }
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("sampling", JSON.toJSONString(mSampling));
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getSaveSamplingUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void deleteSampling(Integer samplingId) {
        isGetData = false;
        isDeletedata = true;
        if (samplingId == null || samplingId < 1) {
            mUpdateListViewListener.showMessage("采样单为空！");
            return;
        }
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("id", samplingId + "");
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(
                    URL.getDeleteSamplingUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
        }
    }
}
